<template>
  <div>
    <div class="el-calendar__header">
      <div class="el-calendar__title">{{ currentMonth }}</div>
      <div class="el-calendar__button-group">
        <div class="el-button-group">
          <button type="button" class="el-button el-button--plain el-button--mini" @click.stop="loadWeekActList(-1)">
            <span>上个周</span>
          </button>
          <button type="button" class="el-button el-button--plain el-button--mini" @click.stop="loadWeekActList(0)">
            <span>今天</span>
          </button>
          <button type="button" class="el-button el-button--plain el-button--mini" @click.stop="loadWeekActList(1)">
            <span>下个周</span>
          </button>
        </div>
      </div>
    </div>
    <div class="el-calendar__body">
      <table cellspacing="0" cellpadding="0" class="el-calendar-table" style="width: 100%; height: 500px">
        <thead>
          <th style="width: 8%"></th>
          <th>
            日
            <span>({{ weekFirst | weekDayFilter(0) }})</span>
          </th>
          <th>
            一
            <span>({{ weekFirst | weekDayFilter(1) }})</span>
          </th>
          <th>
            二
            <span>({{ weekFirst | weekDayFilter(2) }})</span>
          </th>
          <th>
            三
            <span>({{ weekFirst | weekDayFilter(3) }})</span>
          </th>
          <th>
            四
            <span>({{ weekFirst | weekDayFilter(4) }})</span>
          </th>
          <th>
            五
            <span>({{ weekFirst | weekDayFilter(5) }})</span>
          </th>
          <th>
            六
            <span>({{ weekFirst | weekDayFilter(6) }})</span>
          </th>
        </thead>
        <tbody>
          <tr class="el-calendar-table__row">
            <td class="prev">
              <div style="display: flex; justify-content: flex-start; height: 574px">
                <el-timeline :reverse="false">
                  <el-timeline-item v-for="(e, index) in timelineAxis" :key="index" :timestamp="e.timestamp">
                    {{ e.content }}
                  </el-timeline-item>
                </el-timeline>
              </div>
            </td>
            <td v-for="(act, idx) in [week0, week1, week2, week3, week4, week5, week6]" class="prev">
              <div class="act_day">
                <div v-if="[brth0, brth1, brth2, brth3, brth4, brth5, brth6][idx].length > 0" class="act_birthday">
                  <el-popover placement="bottom" width="420" trigger="click">
                    <el-table :data="[brth0, brth1, brth2, brth3, brth4, brth5, brth6][idx]">
                      <el-table-column
                        prop="birthdayCname"
                        label="姓名"
                        align="center"
                        width="80"
                        show-overflow-tooltip></el-table-column>
                      <el-table-column label="类型" align="center" width="60">
                        <template slot-scope="{ row }">
                          <span v-if="row.birthdayType === 1">阳历</span>
                          <span v-else>阴历</span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="kname"
                        label="负责管家"
                        align="center"
                        width="100"
                        show-overflow-tooltip></el-table-column>
                      <el-table-column
                        prop="plan"
                        label="生日计划"
                        align="center"
                        width="100"
                        show-overflow-tooltip></el-table-column>
                      <el-table-column
                        prop="birthdayCcode"
                        label="顾客编号"
                        align="left"
                        width="200"
                        show-overflow-tooltip></el-table-column>
                    </el-table>
                    <el-button slot="reference" type="success" size="mini" round style="background-color: #469b78">
                      生日快乐
                    </el-button>
                  </el-popover>
                </div>
                <div v-for="item in act" class="act_item" :style="calDiv(item)">
                  <div>{{ actTime(item) }}</div>
                  <div>{{ actTitle(item) }}</div>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
import * as actApi from '@/api/activity';
import '@/utils/datefmt';
import { MessageBox } from 'element-ui';
import { mapGetters } from 'vuex';

const axisOfTimeline = [
  {
    content: '',
    timestamp: '09:00',
  },
  {
    content: '',
    timestamp: '10:00',
  },
  {
    content: '',
    timestamp: '11:00',
  },
  {
    content: '',
    timestamp: '12:00',
  },
  {
    content: '',
    timestamp: '13:00',
  },
  {
    content: '',
    timestamp: '14:00',
  },
  {
    content: '',
    timestamp: '15:00',
  },
  {
    content: '',
    timestamp: '16:00',
  },
  {
    content: '',
    timestamp: '17:00',
  },
  {
    content: '',
    timestamp: '18:00',
  },
  {
    content: '',
    timestamp: '19:00',
  },
  {
    content: '',
    timestamp: '20:00',
  },
  {
    content: '',
    timestamp: '21:00',
  },
  {
    content: '',
    timestamp: '22:00',
  },
];

export default {
  name: 'ActivityWeek',
  filters: {
    weekDayFilter(w, val) {
      if (!w) {
        return '';
      }
      const d = new Date(w);
      d.setDate(d.getDate() + val);
      return d.format('MM-dd');
    },
  },
  data() {
    return {
      // 时间轴
      timelineAxis: axisOfTimeline,
      var: 5, // 活动显示定位
      week0: [], // 星期日活动
      week1: [],
      week2: [],
      week3: [],
      week4: [],
      week5: [],
      week6: [], // 星期六活动
      brth0: [], // 星期日过生日
      brth1: [],
      brth2: [],
      brth3: [],
      brth4: [],
      brth5: [],
      brth6: [], // 星期六过生日
      weekFirst: undefined, // 星期日对应的日期
      currentMonth: '',
      dataLoading: false,
    };
  },
  computed: {
    ...mapGetters(['name', 'id', 'deptId', 'openId']),
    innerDivStyle() {
      // 根据 var 计算高度和起始位置
      const height = this.var * 10; // 假设高度是 var 的 10 倍
      const top = this.var * 5; // 假设起始位置是 var 的 5 倍
      return {
        height: `${height}px`,
        top: `${top}px`,
      };
    },
  },
  mounted() {
    // this.flushWeekDay();
  },
  methods: {
    _getCurWeekFirstDate() {
      const d = new Date();
      const w = d.getDay();
      if (w > 0) {
        d.setDate(d.getDate() - w);
      }
      return d;
    },
    searchKeeper: async function (kname) {
      await this.loadWeekActList(2, kname);
    },
    loadWeekActList: async function (val, kname) {
      if (!this.openId) {
        // 不属于任何门店的用户(通常是系统管理员)
        return;
      }
      // -1: pre; 0,undefined: cur; 1: next; 2: keep current
      if (this.dataLoading) {
        return;
      }
      this.dataLoading = true;
      if (val !== 2) {
        this.flushWeekDay(val);
      }
      const d = new Date(this.weekFirst);
      d.setHours(0, 0, 0, 0);
      const start = d.format('yyyy-MM-dd HH:mm:ss');
      d.setDate(d.getDate() + 7);
      const end = d.format('yyyy-MM-dd HH:mm:ss');
      const errAlertMsg = '查询周活动信息失败';
      await actApi
        .getActivitySegment(this.openId, start, end, !!kname ? kname : null, true)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            MessageBox.alert(errAlertMsg);
            return;
          }
          const ret = res.data.data;
          if (ret && ret.actList && ret.actList.length > 0) {
            this.flushWeekAct(ret.actList);
          } else {
            this.flushWeekAct([]);
          }
          if (ret && ret.birthdayPack && ret.birthdayPack.length > 0) {
            this.flushWeekBirthday(ret.birthdayPack);
          } else {
            this.flushWeekBirthday([]);
          }
        })
        .catch(err => {
          console.log(err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    flushWeekAct(list) {
      [this.week0, this.week1, this.week2, this.week3, this.week4, this.week5, this.week6].forEach(x => {
        x.splice(0, x.length);
      });
      if (!list) {
        return;
      }
      list.forEach(x => {
        if (!x.start) {
          return;
        }
        const d = new Date(x.start);
        const w = d.getDay();
        switch (w) {
          case 0:
            this.week0.push(x);
            break;
          case 1:
            this.week1.push(x);
            break;
          case 2:
            this.week2.push(x);
            break;
          case 3:
            this.week3.push(x);
            break;
          case 4:
            this.week4.push(x);
            break;
          case 5:
            this.week5.push(x);
            break;
          case 6:
            this.week6.push(x);
            break;
        }
      });
    },
    flushWeekBirthday(list) {
      [this.brth0, this.brth1, this.brth2, this.brth3, this.brth4, this.brth5, this.brth6].forEach(x => {
        x.splice(0, x.length);
      });
      if (!list) {
        return;
      }
      list.forEach(x => {
        if (!x || !x.length) {
          return;
        }
        const d = new Date(x[0].start);
        const w = d.getDay();
        switch (w) {
          case 0:
            this.brth0.push(...x);
            break;
          case 1:
            this.brth1.push(...x);
            break;
          case 2:
            this.brth2.push(...x);
            break;
          case 3:
            this.brth3.push(...x);
            break;
          case 4:
            this.brth4.push(...x);
            break;
          case 5:
            this.brth5.push(...x);
            break;
          case 6:
            this.brth6.push(...x);
            break;
        }
      });
    },
    flushWeekDay(val) {
      // -1: pre; 0,undefined: cur; 1: next
      if (!val) {
        this.weekFirst = this._getCurWeekFirstDate();
        this.currentMonth = this.weekFirst.format('yyyy 年 MM 月');
        return;
      }
      let d = this.weekFirst;
      if (this.weekFirst === undefined) {
        d = this._getCurWeekFirstDate();
      }
      if (val === -1) {
        d.setDate(d.getDate() - 7);
      } else {
        d.setDate(d.getDate() + 7);
      }
      this.currentMonth = d.format('yyyy 年 MM 月');
      this.weekFirst = d;
      return;
    },
    calDiv(item) {
      if (!item) {
        return {};
      }
      const start = new Date(item.start);
      const baseTime = new Date(item.start);
      baseTime.setHours(9);
      baseTime.setMinutes(0);
      baseTime.setSeconds(0);
      let end = new Date(item.start).setHours(start.getHours() + 1); // 如果没有设置活动结束时间, 默认绘制 1 小时的高度
      if (!!item.end) {
        end = new Date(item.end);
      }

      // 计算两个时间点之间的分钟数
      const durationMinutes = (end - start) / (1000 * 60);
      // 计算从 09:00 到开始时间的分钟数
      const offsetMinutes = (start - baseTime) / (1000 * 60);
      // 每分钟的高度
      const heightPerMinute = 41 / 60;
      // 计算两个时间点之间的高度
      const divHeight = durationMinutes * heightPerMinute;
      // 计算从 09:00 到开始时间的高度
      const offsetHeight = offsetMinutes * heightPerMinute;

      const color_salon = '#724EFF';
      const bgcolor_salon = '#F5F5FF';
      const color_gift = '#F29339';
      const bgcolor_gift = '#FFF5F5';
      const color_other = '#FF5B5B';
      const bgcolor_other = '#FFF5F5';
      const color_birthday = '#469b78';

      const styl = {
        height: '' + divHeight + 'px',
        top: '' + offsetHeight + 'px',
        left: '0px',
      };
      if (item.scheme == 1) {
        styl['color'] = color_salon;
        styl['background-color'] = bgcolor_salon;
      } else if (item.scheme == 2) {
        styl['color'] = color_gift;
        styl['background-color'] = bgcolor_gift;
      } else if (item.scheme == 3) {
        styl['color'] = color_birthday;
        styl['background-color'] = bgcolor_gift;
      } else {
        styl['color'] = color_other;
        styl['background-color'] = bgcolor_other;
      }
      return styl;
    },
    actTime: function (item) {
      if (!item) {
        return '';
      }
      let t = item.start.substring(11, 16);
      if (!!item.end) {
        t = t + '-' + item.end.substring(11, 16);
      }
      return t;
    },
    actTitle: function (item) {
      if (!item) {
        return '';
      }
      let type = '其他';
      if (item.scheme == 1) {
        type = '沙龙';
      } else if (item.scheme == 2) {
        type = '客情';
      } else if (item.scheme == 3) {
        type = '生日';
        if (!item.birthdayType) {
          return `${type}-${item.birthdayCname}-${item.kname}`;
        }
        if (item.birthdayType === 1) {
          return `${type}(阳历)-${item.birthdayCname}-${item.kname}`;
        }
        if (item.birthdayType === 2) {
          return `${type}(农历)-${item.birthdayCname}-${item.kname}`;
        }
      }
      return type + '-' + item.kname;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-timeline {
  padding-inline-start: 10px;
}

.act_day {
  width: 100%;
  height: 533px;
  position: relative;
}

.act_birthday {
  width: 30%;
  position: absolute;
  left: 1px;
  top: 1px;
  z-index: 3001;
}

.act_item {
  width: 100%;
  position: absolute;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  gap: 1px;
}
</style>
